package com.gyms.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.classic.okhttp.AppChangeUtils;
import com.classic.okhttp.Cons;
import com.classic.okhttp.beans.HVRefundConfigBean;
import com.classic.okhttp.beans.HVVersionBean;
import com.classic.okhttp.enums.Enum;
import com.classic.okhttp.services.ICommonService;
import com.classic.okhttp.services.IUserService;
import com.classic.okhttp.zmoumall.http.ObjectCallback;
import com.classic.okhttp.zmoumall.utils.ToastUtil;
import com.gyms.R;
import com.gyms.base.BaseActivity;
import com.gyms.base.MyAutoLayoutActivity;
import com.gyms.constant.Constants;
import com.gyms.manager.AndroidJavaScript;
import com.gyms.manager.CommonDialogUtils;
import com.gyms.manager.StateUtils;
import com.gyms.manager.TitleManager;
import com.gyms.manager.WebViewManger;
import com.gyms.view.bottomview.ShareDialog;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.LockSupport;

import butterknife.BindView;
import butterknife.OnClick;
import constant.EventConstant;
import constant.PicSplit;
import utils.AppUtils;
import utils.DateUtil;
import utils.StringUtils;
import weight.ComDialog;
import weight.UiEvent;

/**
 * 网页浏览Activity yjl
 */
public class WebViewActivity extends MyAutoLayoutActivity implements View.OnClickListener {

    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    @BindView(R.id.wb_webview)
    WebView wbWebview;
    @BindView(R.id.tv_title)
    TextView mTvTitle;

    private ShareDialog mShareDialog;
    private WebViewManger mWebViewManger;//webview相关设置Manger
    private String url = "";
    private String title;
    private boolean isRevertDetail;//是否是退款详情
    private ArrayList<HVRefundConfigBean> mRefundConfigs;
    private String mVenueItemSpecific;
    private Intent mIntent;

    private String mShareTitle;//分享标题
    private String mShareContent;//分享内容
    private String mShareUrl;//分享链接

    private ImageView mIvShare;

    private TextView mTvAfterBack;

    //升级框相关
    private boolean outSideCancel=true;

    private boolean isCancelGone=false;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_web_view;
    }

    @Override
    protected void initView() {
        title = getIntent().getStringExtra(Constants.S_KEY_TITLE);
        url = getIntent().getStringExtra(Constants.S_KEY_URL);
        Bundle mBundle = getIntent().getExtras();
        if (null != mBundle) {
            isRevertDetail = mBundle.getBoolean(Constants.GO_RULE_DETAIL);
            mRefundConfigs = (ArrayList<HVRefundConfigBean>) mBundle.getSerializable(Constants.WEBVIEW_CONFIGS_LIST);
            mVenueItemSpecific = mBundle.getString(Constants.WEBVIEW_STR_HTML);
        }
        mTvTitle.setText(title);
        doInitView();
        mTvAfterBack= mTitleManager.mAfterBack;
        mTvAfterBack.setText("后退");
        setBack();
    }

    private void doInitView() {
        mIvShare=mTitleManager.setRightViewR(R.mipmap.icon_fenxiang);
        mIvShare.setVisibility(View.GONE);
    }

    @Override
    protected void setTitleTheme() {
        mTheme = TitleManager.TitleTheme.White;
    }

    @Override
    protected void setListener() {
        EventBus.getDefault().register(this);
        mWebViewManger = WebViewManger.getInstance(this);
        mWebViewManger.setWebViewSetting(wbWebview, url, progressBar, isRevertDetail, mRefundConfigs, mVenueItemSpecific,title,mTvTitle,mTvAfterBack);
        mIvShare.setOnClickListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        UMShareAPI.get(this).release();
    }

    @Override
    protected void processLogic() {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void close(UiEvent mUiEvent) {
        if (EventConstant.S_WEBVIEW_CLONSE.equals(mUiEvent.getKey())) {//关掉页面
            finish();
        } else if (EventConstant.S_WEBVIEW_SETTITLE.equals(mUiEvent.getKey())) {//设置标题
            String title = (String) mUiEvent.getObject();
            mTvTitle.setText(title);
        } else if (EventConstant.S_WEBVIEW_START_ACTIVITY.equals(mUiEvent.getKey())) {
            List<Object> mKeyLists = (List<Object>) mUiEvent.getObject();
            if (!StringUtils.isNull(mKeyLists)) {
                String mKeyStr = (String) mKeyLists.get(0);
                if (mKeyStr.equals(EventConstant.FLAG_GO_LOGIN)) {//登录
                    mIntent = new Intent(mContext, CodeLoginActivity.class);
                    ((BaseActivity) mContext).startActivity(mIntent, false);

                } else if (mKeyStr.equals(EventConstant.FLAG_GO_GYM_DETAIL)) {//场馆详情
                    String mGymId = (String) mKeyLists.get(1);
                    Intent mIntent = new Intent(mContext, GymDetailActivity.class);
                    mIntent.putExtra(Constants.FLAG_INTENT_VENUEID, mGymId);
                    startActivity(mIntent, false);

                } else if (mKeyStr.equals(EventConstant.FLAG_GO_COURSE_DETAIL)) {// 课程详情
                    String mCourseId = (String) mKeyLists.get(1);
                    mIntent = new Intent(mContext, ProductDetailsActivity.class);
                    mIntent.putExtra(Constants.FALG_INTENT_PRPDUCT_ID, mCourseId);
                    startActivity(mIntent, false);

                } else if (mKeyStr.equals(EventConstant.FLAG_GO_MY_ORDER)) {//我的订单

                    mIntent = new Intent(mContext, MyOrderActivity.class);
                    startActivity(mIntent,false);

                } else if (mKeyStr.equals(EventConstant.FLAG_GO_MY_CARDACTIVITY)) {//我的卡卷

                    mIntent = new Intent(mContext, MyCouponActivityNew.class);
                    startActivity(mIntent,false);

                } else if (mKeyStr.equals(EventConstant.FLAG_SHOW_SHARE_DIALOG)) {//显示分享框
                     mShareTitle = (String) mKeyLists.get(1);
                     mShareContent = (String) mKeyLists.get(2);
                     mShareUrl = (String) mKeyLists.get(3);
//                    doShowShare(mShareTitle, mShareContent, mShareUrl);
                    if(AppChangeUtils.isGymApp){//呼啦场馆显示 并且返回true
                        mIvShare.setVisibility(View.VISIBLE);
                    }else{//呼啦场馆通 返回false 隐藏
                        mIvShare.setVisibility(View.GONE);
                    }
                } else if (mKeyStr.equals(EventConstant.FLAG_DISMISS_SHARE_DIALOG)) {//隐藏分享框

                    mIvShare.setVisibility(View.GONE);

                } else if (mKeyStr.equals(EventConstant.FLAG_GO_CHOSESEAT)) {//订座
                    String gymId = (String) mKeyLists.get(1);
                    String projectId = (String) mKeyLists.get(2);
                    int time = (int) mKeyLists.get(3);
                    mIntent = new Intent(mContext, SeatChoseActivity.class);
                    mIntent.putExtra(Constants.FLAG_INTENT_VENUEID, gymId);
                    mIntent.putExtra(Constants.FLAG_INTENT_PROJECT_ID, projectId);
                    mIntent.putExtra(Constants.FLAG_INTENT_CHOSE_TIME, time);
                    startActivity(mIntent, false);
                }

            }
        }else if(mUiEvent.getKey().equals("js")){//js闭包
            String mFun= (String) mUiEvent.getObject();
            wbWebview.loadUrl(PicSplit.makeFunctionStr(mFun,Cons.mStep));
        }else if(mUiEvent.getKey().equals(EventConstant.FLAG_LOGIN_ED)){//已经登录的回调
            String mFun= (String) mUiEvent.getObject();
            wbWebview.loadUrl(PicSplit.makeFunctionStr(mFun,Constants.JS_LOGIN_ED));
        } else if(mUiEvent.getKey().equals(EventConstant.FLAG_UN_LOGIN)){//未登录
            String mFun= (String) mUiEvent.getObject();
            Intent mIntent =new Intent(mContext,CodeLoginActivity.class);
            mIntent.putExtra(Constants.KEY_LOGIN_FUN,mFun);
            mContext.startActivity(mIntent);
        }else if(mUiEvent.getKey().equals(EventConstant.FLAG_LOGIN_SUCCESS)){//登录成功
            String mFun= (String) mUiEvent.getObject();
            wbWebview.loadUrl(PicSplit.makeFunctionStr(mFun,Constants.JS_LOGIN_SUCCESS));
        } else if(mUiEvent.getKey().equals(EventConstant.FLAG_LOGIN_CANCEL)){//取消
            String mFun= (String) mUiEvent.getObject();
            wbWebview.loadUrl(PicSplit.makeFunctionStr(mFun,Constants.JS_LOGIN_CANCEL));
        }else if(mUiEvent.getKey().equals(EventConstant.FLAG_SAVE_TODAY_STEP_COUNT)){//保存当日步数
            String mFun= (String) mUiEvent.getObject();
            doSaveTodayStep(mFun);
        }else if(mUiEvent.getKey().equals(EventConstant.FLAG_SHOW_LOADING_HUD)){//showLoading
            if (null == loadingView) {
                createLoadingView("加载中", false);
            }
            loadingView.show();
        }else if(mUiEvent.getKey().equals(EventConstant.FLAG_HIDE_HUD)){//关闭loading
           if(null!=loadingView){
               loadingView.dismiss();
           }
        }else if(mUiEvent.getKey().equals(EventConstant.FLAG_SHOW_ALERT)){//弹出框
            List<Object> mObjectList= (List<Object>) mUiEvent.getObject();
            String mMessage= (String) mObjectList.get(0);
            final Thread mCurLockThread= (Thread) mObjectList.get(1);//当前阻塞的子线程
            final ComDialog mJsDialog=CommonDialogUtils.dialog(WebViewActivity.this,getSupportFragmentManager(),getString(R.string.app_name),mMessage);
            mJsDialog.setCancelGone();
            mJsDialog.setSubmit(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mJsDialog.dismiss();
                    LockSupport.unpark(mCurLockThread);//唤醒子线程
                }
            });


        }else if(mUiEvent.getKey().equals(EventConstant.FLAG_SHOW_CONFIRM)){// 弹出框
            List<Object> mObjectList= (List<Object>) mUiEvent.getObject();
            String mMessage= (String) mObjectList.get(0);
            final Handler mHandler= (Handler) mObjectList.get(1);
            final Message mMes=Message.obtain();
            final ComDialog mJsDialog=CommonDialogUtils.dialog(WebViewActivity.this,getSupportFragmentManager(),getString(R.string.app_name),mMessage);
            mJsDialog.setSubmit(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mJsDialog.dismiss();
                    mMes.what= 0;
                    mMes.obj=true;
                    mHandler.sendMessage(mMes);
                }
            });
            mJsDialog.setCancel(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mJsDialog.dismiss();
                    mMes.what= AndroidJavaScript.S_COMMIT;
                    mMes.obj=false;
                    mHandler.sendMessage(mMes);
                }
            });

        }else if(mUiEvent.getKey().equals(EventConstant.FLAG_PHONE_NUM)){//拨打电话
            String mPhoneNum= (String) mUiEvent.getObject();
            StateUtils.callMobilePhone(WebViewActivity.this,mPhoneNum);
        }else if(mUiEvent.getKey().equals(EventConstant.FLAG_DO_SHOW_SHARE_DIALOG)){//弹出单个弹出框或者直接分享
            List<Object> mShareList= (List<Object>) mUiEvent.getObject();
           String mTitle= (String) mShareList.get(0);
           String mContent= (String) mShareList.get(1);
           String mUrl= (String) mShareList.get(2);
           int mShareType= (int) mShareList.get(3);
           String mCallBackFunStr= (String) mShareList.get(4);
           doShowShareDialog(mTitle,mContent,mUrl,mShareType,mCallBackFunStr);
        }else if(mUiEvent.getKey().equals(EventConstant.FLAG_TRY_UPDATE)){//尝试更新
            initUpdate();
        }
    }

    /**
     *弹出分享框或者 直接分享渠道
     * @param mTitle title
     * @param mContent content
     * @param mUrl mUrl
     * @param mShareType mShareType 0 弹出分享框 ，1，2，3对应的分享渠道
     * @param mCallBackFunStr mCallBackFunStr
     */

    private void doShowShareDialog(String mTitle, String mContent, String mUrl, int mShareType, String mCallBackFunStr) {
        doShowShare(mTitle,mContent,mUrl);
        mShareDialog.setCallBack(mCallBackFunStr,wbWebview);
        if(0==mShareType){
            mShareDialog.show();
        }else {
            SHARE_MEDIA platform =StateUtils.getShareMedia(mShareType);
            mShareDialog.doShare(platform);
        }
    }

    /**
     * 保存今日步数
     * @param mFun 回调
     */

    private void doSaveTodayStep(final String mFun) {
        if (null == loadingView) {
            createLoadingView("加载中", false);
        }
        loadingView.show();
        IUserService.reportWalk(this, DateUtil.getDayBegin(), Cons.mStep, false, new ObjectCallback<Object>() {
            @Override
            public void onSuccess(Object response, String message) {
                loadingView.dismiss();
                doJsSaveCall(mFun,true);
            }

            @Override
            public void onErrorT(int code, Object response, String errorMessage) {
                loadingView.dismiss();
                doJsSaveCall(mFun,false);
                ToastUtil.showToast(mContext,errorMessage);
            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                loadingView.dismiss();
                doJsSaveCall(mFun,false);
            }
        });
    }

    private void doJsSaveCall(String mFun, boolean isSuccess) {
        wbWebview.loadUrl(PicSplit.makeFunctionStr(mFun,isSuccess));
    }


    /**
     * @param title title
     * @param content content
     * @param url url
     */

    private void doShowShare(final String title, final String content, final String url) {
        if(null==mShareDialog){
            mShareDialog = new ShareDialog(mContext, R.style.BottomToTopAnim);
        }
        mShareDialog.setShareContent(content);
        mShareDialog.setTagUrl(url);
        mShareDialog.setTitle(title);
    }




    @OnClick(R.id.tv_right)
    public void onViewClicked() {//显示出分享框
        doShowShare(mShareTitle, mShareContent, mShareUrl);
        mShareDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_img_right_right:
                doShowShare(mShareTitle, mShareContent, mShareUrl);
                mShareDialog.show();
                break;
        }
    }

    /**
     * 检查版本升级
     */
    private void initUpdate() {
        if(null!=loadingView){
            loadingView.show();
        }
        String version = AppUtils.getAppVersionName(mContext);
        final String channel =AppUtils.getPacketChannelName(mContext) ;
        ICommonService.checkVersion(this, version, channel, Enum.EnumPlatform.Android, true,false, new ObjectCallback<HVVersionBean>() {
            @Override
            public void onSuccess(final HVVersionBean response, String message) {
                if (loadingView != null) {
                    loadingView.dismiss();
                }
                if(StringUtils.isNull(response)){
                    return;
                }
                if(response.getAction()==Enum.EnumVersion.None||response.getAction()==Enum.EnumVersion.Newest){
                    return;
                }
                switch (response.getAction()) {
                    case Force:// 强制升级
                        outSideCancel=false;
                        isCancelGone=true;
                        break;
                    case Prompt://提示升级
                        break;
                }
                final  ComDialog updateDialog= CommonDialogUtils.dialog(WebViewActivity.this,getSupportFragmentManager(),getString(R.string.str_update),"为了更好的体验,请更新至最新版本","确定", "取消");
                if(isCancelGone){
                    updateDialog.setCancelGone();
                }
                updateDialog.setSubmit(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Uri uri;
                        if(StringUtils.isHttpPic(response.getUrl())){
                            uri = Uri.parse(response.getUrl());
                        }else {
                            uri = Uri.parse(Cons.URL_DOWNLOAD);
                        }
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        startActivity(intent,false);
                       /* if(outSideCancel){
                            updateDialog.dismiss();
                        }*/
                    }
                });
            }

            @Override
            public void onErrorT(int code, HVVersionBean response, String errorMessage) {
                if (loadingView != null) {
                    loadingView.dismiss();
                }
                ToastUtil.showToast(mContext, errorMessage);
            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                if (loadingView != null) {
                    loadingView.dismiss();
                }
            }
        });
    }
}
